Popular Searches
Popular Course Categories
Popular Courses

Introduction to Spring Framework Architecture

Introduction to Spring Framework Architecture

Spring Framework and Dependency Injection

Introduction to Spring Framework Architecture

Course: Advance Java Training

Topic: Introduction to Spring Framework Architecture

Course Link: Advance Java Training Course – JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to the Spring Framework

The Spring Framework is a powerful, open-source Java framework used to develop enterprise applications, web applications, REST APIs, and database-driven systems. It provides infrastructure and reusable components that help developers build applications with less boilerplate code and better separation of responsibilities.

Spring simplifies important application development tasks such as dependency management, transaction handling, database access, web request processing, security integration, and automated testing. It allows developers to focus on business logic instead of manually managing every infrastructure concern.

The architecture of Spring is modular. Developers can use individual modules according to application requirements instead of using every feature in every project.

Why Is Spring Used?

  • To develop maintainable and scalable Java applications.
  • To reduce tight coupling between application components.
  • To manage objects and their dependencies automatically.
  • To simplify database operations and transaction management.
  • To build web applications and RESTful services.
  • To support unit testing and integration testing.
  • To integrate technologies such as Hibernate, JPA, JDBC, and messaging systems.

Example Applications

  • E-commerce applications and order management systems.
  • Banking and financial management applications.
  • Employee management systems.
  • Inventory and warehouse applications.
  • REST APIs for web and mobile applications.
  • Enterprise business applications.

2. Learning Objectives

After completing this topic, learners should be able to:

  • Explain the purpose and importance of the Spring Framework.
  • Understand the major layers and modules of Spring architecture.
  • Explain Inversion of Control (IoC) and Dependency Injection (DI).
  • Understand Spring beans and the IoC container.
  • Differentiate between BeanFactory and ApplicationContext.
  • Understand the roles of Spring AOP, Spring MVC, and the data access modules.
  • Explain how a request moves through a Spring MVC application.
  • Develop a basic Spring application using annotations and Java configuration.
  • Understand how Spring integrates with databases and testing tools.

3. What Is Spring Framework Architecture?

Spring Framework architecture refers to the organization of Spring's modules, containers, and supporting services. These components work together to manage Java objects, process requests, interact with databases, apply cross-cutting functionality, and support testing.

The architecture is modular, meaning that developers can select the features required by their applications. For example, a command-line Java application may need only the Spring Core Container, while a web application may also use Spring MVC and Spring's data access and transaction modules.

Major Architectural Components

Component Purpose Example
Core Container Manages objects, dependencies, and application configuration. IoC, DI, Spring beans
AOP Separates cross-cutting concerns from business logic. Logging, method interception
Data Access and Integration Simplifies database operations and transaction management. JDBC, ORM, transactions
Web Layer Supports web applications and HTTP request processing. Spring MVC, REST controllers
Messaging and Integration Supports message-based communication and integrations. JMS, messaging abstractions
Testing Supports testing Spring-managed components and applications. Spring TestContext, MockMvc

These components are not necessarily arranged as rigid runtime layers. They are logical groups of related capabilities that applications combine according to their needs.


4. Overview of Spring Framework Architecture

The following conceptual diagram shows how the major parts of a typical Spring-based application work together.

+------------------------------------------------------+
|                   Application Layer                  |
|       Controllers | Services | Repositories          |
+------------------------------------------------------+
                         |
                         v
+------------------------------------------------------+
|                  Spring Core Container               |
|       IoC Container | Beans | Context | SpEL          |
+------------------------------------------------------+
                         |
          +--------------+--------------+
          |              |              |
          v              v              v
+----------------+ +-------------+ +------------------+
|  Spring AOP    | |  Data Access| |    Web Layer     |
| Logging        | | JDBC / ORM  | | Spring MVC       |
| Transactions   | | Transactions| | REST APIs        |
+----------------+ +-------------+ +------------------+
                         |
                         v
+------------------------------------------------------+
|                 External Resources                   |
|          Databases | Services | Message Systems      |
+------------------------------------------------------+
                         |
                         v
+------------------------------------------------------+
|               Testing and Integration                |
|     Unit Tests | Integration Tests | MockMvc          |
+------------------------------------------------------+

Note: This is a conceptual view, not a strict execution sequence. Spring AOP, transactions, web processing, and data access interact in different ways depending on the application configuration.


5. Core Container Module

The Core Container is the foundation of Spring Framework architecture. It provides the mechanisms used to create, configure, manage, and connect application objects.

The main modules include Spring Core, Spring Beans, Spring Context, and Spring Expression Language (SpEL).

5.1 Spring Core

Spring Core provides fundamental utilities and infrastructure used by other Spring modules. It supports the framework's core programming model and contributes to dependency injection and resource handling.

Main responsibilities:

  • Provides core framework utilities.
  • Supports foundational dependency management features.
  • Provides infrastructure used by other Spring modules.

5.2 Spring Beans

The Spring Beans module provides the infrastructure for defining and managing Spring beans. A bean is an object that is instantiated, configured, and managed by a Spring IoC container.

Beans can represent services, repositories, controllers, configuration objects, or other application components.

import org.springframework.stereotype.Component;

@Component
public class MessageService {

    public String getMessage() {
        return "Welcome to Spring Framework";
    }
}

The @Component annotation marks the class as a candidate for component scanning. When component scanning is configured correctly, Spring can discover and register it as a bean.

5.3 Spring Context

The Spring Context module builds on the bean infrastructure and provides the ApplicationContext interface. It supports application events, resource loading, internationalization, and access to managed beans.

Example:

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainApplication {

    public static void main(String[] args) {
        ApplicationContext context =
            new AnnotationConfigApplicationContext(
                AppConfig.class
            );

        MessageService service =
            context.getBean(MessageService.class);

        System.out.println(service.getMessage());
    }
}

This example assumes that AppConfig is configured to scan the package containing MessageService.

5.4 Spring Expression Language (SpEL)

SpEL is an expression language that supports querying and manipulating object values at runtime. It can access properties, call methods, evaluate expressions, and reference beans in supported Spring configuration contexts.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ApplicationInfo {

    @Value("#{2 + 3}")
    private int result;

    public int getResult() {
        return result;
    }
}

In this example, Spring evaluates the expression and injects the result into the field.


6. Inversion of Control (IoC)

Inversion of Control is a design principle in which responsibility for creating and managing objects is transferred from application code to a framework or container.

In a traditional Java application, a class may create its dependencies directly using the new keyword. In Spring, the container can create the required objects and supply their dependencies.

Traditional Java Approach

class EmailService {

    public void sendEmail() {
        System.out.println("Email sent");
    }
}

class NotificationManager {

    private EmailService emailService =
        new EmailService();

    public void notifyUser() {
        emailService.sendEmail();
    }
}

The NotificationManager directly creates an EmailService object. This makes it harder to replace the email implementation or provide a test double without changing the class.

Spring-Based Approach

import org.springframework.stereotype.Component;

@Component
class EmailService {

    public void sendEmail() {
        System.out.println("Email sent");
    }
}
import org.springframework.stereotype.Component;

@Component
class NotificationManager {

    private final EmailService emailService;

    public NotificationManager(
            EmailService emailService) {
        this.emailService = emailService;
    }

    public void notifyUser() {
        emailService.sendEmail();
    }
}

Spring can create both objects and inject the EmailService dependency into the NotificationManager, provided that component scanning or equivalent bean configuration is in place.

Benefits of IoC

  • Reduces tight coupling between classes.
  • Improves code maintainability.
  • Makes unit testing easier.
  • Centralizes object configuration and lifecycle management.
  • Allows implementations to be replaced with less application-code modification.

7. Dependency Injection (DI)

Dependency Injection is a technique for supplying an object with the other objects it needs to perform its responsibilities. Spring uses its IoC container to perform dependency injection.

IoC describes the broader principle of transferring control to the framework, while DI is a common mechanism used to implement that principle.

7.1 Constructor Injection

Constructor injection supplies dependencies through a class constructor. It is generally preferred for required dependencies because it supports immutable fields and makes the class's requirements explicit.

import org.springframework.stereotype.Service;

@Service
public class PaymentService {

    public void processPayment() {
        System.out.println("Payment processed");
    }
}
import org.springframework.stereotype.Service;

@Service
public class OrderService {

    private final PaymentService paymentService;

    public OrderService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    public void placeOrder() {
        paymentService.processPayment();
        System.out.println("Order placed");
    }
}

7.2 Setter Injection

Setter injection supplies a dependency through a setter method. It can be useful for optional dependencies that do not need to be present when the object is created.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ReportManager {

    private ReportExporter reportExporter;

    @Autowired
    public void setReportExporter(
            ReportExporter reportExporter) {
        this.reportExporter = reportExporter;
    }
}

The example assumes that ReportExporter is available as a Spring bean.

7.3 Field Injection

Field injection places a dependency directly into a field using an annotation. Although supported, it is generally less suitable for application code because dependencies are less visible and straightforward unit testing can become more difficult.

@Autowired
private PaymentService paymentService;

Comparison of Dependency Injection Types

Injection Type How It Works Typical Use
Constructor Dependencies are passed to the constructor. Required dependencies; recommended default.
Setter Dependencies are supplied through setter methods. Optional or changeable dependencies.
Field Spring injects dependencies into fields. Supported, but generally less preferred.

8. Spring IoC Container

The IoC container is one of the most important components of Spring architecture. It creates and manages beans, resolves dependencies, applies configuration, and manages bean lifecycles according to their scopes and configuration.

The two key container interfaces are BeanFactory and ApplicationContext.

8.1 BeanFactory

BeanFactory provides the fundamental container functionality for managing and retrieving beans. It is useful when a lightweight bean factory is sufficient.

8.2 ApplicationContext

ApplicationContext extends the basic bean factory capabilities with additional application infrastructure, including event publication, message resolution, and resource access.

It is the commonly used container in typical Spring applications.

BeanFactory vs. ApplicationContext

Feature BeanFactory ApplicationContext
Primary role Basic bean management. Bean management plus application services.
Events No built-in application event publisher contract comparable to ApplicationContext. Supports application event publication.
Internationalization No built-in MessageSource contract. Supports message resolution through MessageSource.
Typical usage Specialized or lightweight scenarios. Most standard Spring applications.

How the Container Works

  1. Spring reads configuration from annotations, Java configuration, XML, or other supported sources.
  2. The container registers bean definitions.
  3. It creates bean instances when required by the configured lifecycle.
  4. It resolves and injects dependencies.
  5. It applies relevant bean post-processors and framework features.
  6. It makes beans available for application use.
  7. For applicable singleton beans, it invokes configured destruction callbacks when the container shuts down.

9. Spring Bean Lifecycle

The bean lifecycle describes the stages through which a Spring-managed object passes, from creation to eventual destruction when applicable.

Typical Lifecycle Stages

  1. Instantiation: Spring creates the bean instance.
  2. Dependency population: Spring supplies configured dependencies.
  3. Aware callbacks: Applicable interfaces can provide container-related information.
  4. Before-initialization processing: Bean post-processors can modify or wrap the bean.
  5. Initialization callbacks: Methods such as @PostConstruct and configured initialization methods may run.
  6. After-initialization processing: Post-processors may return a proxy or another object in place of the original bean.
  7. Usage: Application components use the managed bean.
  8. Destruction: Applicable destruction callbacks run when the container manages the bean's shutdown.

Lifecycle Example

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;

@Component
public class ApplicationResource {

    @PostConstruct
    public void initialize() {
        System.out.println("Resource initialized");
    }

    public void execute() {
        System.out.println("Resource is being used");
    }

    @PreDestroy
    public void cleanup() {
        System.out.println("Resource cleanup");
    }
}

In modern Jakarta-based applications, jakarta.annotation provides these annotations when the required dependency is available. Older Spring applications may use the corresponding javax.annotation package.

Destruction callbacks are not automatically guaranteed for every bean scope. For example, Spring does not manage the complete destruction lifecycle of prototype-scoped beans after handing them to the caller.


10. Spring Bean Scopes

A bean scope determines how Spring creates and shares instances of a bean.

Scope Description Common Use
singleton One shared instance per bean definition within a container. Stateless services and repositories.
prototype A new instance is created whenever the container is asked for the bean. Objects that require separate instances.
request One instance per HTTP request in a web-aware context. Request-specific information.
session One instance per HTTP session. Session-specific state.
application One instance per ServletContext in a web application. Web-application-level state.
websocket One instance per WebSocket session. WebSocket session state.

Important: Singleton scope does not automatically make a bean thread-safe. Shared singleton services should generally avoid mutable request-specific state in instance fields.


11. Aspect-Oriented Programming (AOP)

Aspect-Oriented Programming helps separate cross-cutting concerns from core business logic. Cross-cutting concerns are functionalities that affect multiple parts of an application.

Examples include logging, transaction boundaries, performance monitoring, and certain authorization checks.

Important AOP Terminology

  • Aspect: A module that contains cross-cutting behavior.
  • Advice: The action performed at a selected execution point.
  • Join point: A point during program execution where advice may apply. In Spring's proxy-based AOP, method executions are the primary supported join points.
  • Pointcut: A predicate that selects join points.
  • Target object: The object whose behavior is being advised.
  • Proxy: An object through which Spring can intercept supported method calls.

Example of Logging with AOP

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.example.service.*.*(..))")
    public void logBeforeServiceMethod() {
        System.out.println(
            "A service method is about to execute"
        );
    }
}

This example requires Spring AOP and AspectJ annotation support to be configured. The pointcut targets methods in the specified service package.

Benefits of AOP

  • Reduces duplicated logging and monitoring code.
  • Separates infrastructure behavior from business logic.
  • Supports declarative transaction management.
  • Improves maintainability when cross-cutting rules are centralized.

Spring's proxy-based AOP has limitations. For example, a method call made from one method to another method on the same object generally bypasses the proxy, so the expected advice may not execute for that internal call.


12. Spring Data Access and Integration Layer

The data access and integration modules simplify interaction with databases, object-relational mapping frameworks, messaging systems, and transaction infrastructure.

12.1 Spring JDBC

Spring JDBC simplifies traditional JDBC operations by handling repetitive tasks such as resource management, statement execution, and exception translation.

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDao {

    private final JdbcTemplate jdbcTemplate;

    public EmployeeDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Integer getEmployeeCount() {
        return jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM employees",
            Integer.class
        );
    }
}

This example assumes that a suitable DataSource and database schema are configured.

12.2 Spring ORM

Spring ORM integrates Spring with object-relational mapping technologies such as Hibernate and JPA. It supports integration with persistence infrastructure and Spring-managed transactions.

ORM frameworks map Java objects to relational database records, reducing the need to manually map every result row.

12.3 Spring Transaction Management

Transaction management helps ensure that related database operations are committed or rolled back according to application requirements.

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TransferService {

    @Transactional
    public void transferMoney() {
        // Debit one account.
        // Credit another account.
        // Both operations should participate
        // in the configured transaction.
    }
}

The example illustrates transaction declaration only; actual debit and credit operations, transaction-manager configuration, and appropriate rollback rules must be implemented.

12.4 Spring Messaging

Spring provides abstractions and integrations for message-based communication. Depending on the selected modules and external infrastructure, applications can send and receive messages asynchronously.

Benefits of the Data Access Layer

  • Reduces repetitive database-access code.
  • Integrates with Hibernate and JPA.
  • Provides consistent transaction-management support.
  • Helps separate persistence logic from business services.
  • Supports testing with controlled database dependencies.

13. Spring Web Layer

The Spring Web layer provides functionality for developing web applications, processing HTTP requests, and building REST APIs. Spring MVC is a widely used web framework built on the Servlet API.

The main components commonly used in a layered Spring MVC application are controllers, services, and repositories.

13.1 Controller Layer

The controller handles incoming requests, validates or binds input as configured, invokes the service layer, and returns a view or response body.

13.2 Service Layer

The service layer contains business rules and coordinates operations between repositories and other components.

13.3 Repository Layer

The repository layer manages persistence operations, including saving, retrieving, updating, and deleting application data.

Typical Request Flow

Client
  |
  v
DispatcherServlet
  |
  v
Handler Mapping
  |
  v
Controller
  |
  v
Service
  |
  v
Repository / DAO
  |
  v
Database
  |
  v
Response returned to the client

How Spring MVC Processes a Request

  1. A client sends an HTTP request to the application.
  2. The Servlet container forwards the request to Spring's DispatcherServlet.
  3. Handler mapping identifies the appropriate controller method.
  4. Spring invokes the selected controller handler through the configured MVC infrastructure.
  5. The controller calls the service layer to execute business logic.
  6. The service may call a repository to access the database.
  7. The result is returned to the controller.
  8. For REST endpoints, message converters commonly serialize the response into JSON or another supported representation.
  9. The HTTP response is sent back to the client.

Example REST Controller

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WelcomeController {

    @GetMapping("/welcome")
    public String welcome() {
        return "Welcome to Spring MVC";
    }
}

When the application is running and the route is available, a GET request to /welcome returns the response text.

Spring MVC vs. Spring WebFlux

Feature Spring MVC Spring WebFlux
Programming model Servlet-based, commonly imperative. Reactive, supporting non-blocking request processing.
Common return types Objects, strings, ResponseEntity. Mono, Flux, and supported reactive types.
Typical use Traditional web applications and REST APIs. Applications that benefit from reactive and non-blocking processing.

Both frameworks can support REST APIs. The appropriate choice depends on workload, dependencies, team experience, and the need for reactive processing.


14. Spring Configuration Approaches

Spring supports multiple ways to define beans and configure application behavior. Modern applications commonly use annotations and Java-based configuration, although XML configuration is still supported.

14.1 XML-Based Configuration

XML configuration defines bean definitions in an XML file.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="messageService"
          class="com.example.MessageService"/>

</beans>

14.2 Annotation-Based Configuration

Annotations such as @Component, @Service, @Repository, and @Controller help identify classes for component scanning.

@Service
public class CustomerService {
    public String getCustomerStatus() {
        return "Active";
    }
}

14.3 Java-Based Configuration

Java configuration uses @Configuration and @Bean to declare beans in Java code.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public MessageService messageService() {
        return new MessageService();
    }
}

In this example, Spring registers the object returned by the @Bean method as a managed bean.

Comparison of Configuration Approaches

Approach Advantages Considerations
XML Centralized external configuration. Can become verbose for large applications.
Annotations Places component metadata near the class. Requires component scanning or explicit registration.
Java configuration Type-safe bean declarations and flexible configuration. Requires configuration classes and methods.

15. Spring Framework vs. Spring Boot

Spring Framework provides the core programming model and infrastructure for Java applications. Spring Boot builds on Spring Framework and simplifies application setup through auto-configuration, starter dependencies, and convenient application-running options.

Feature Spring Framework Spring Boot
Purpose Provides core application infrastructure and modules. Simplifies the setup and development of Spring applications.
Configuration Can require more explicit configuration depending on the project. Provides auto-configuration based on dependencies and settings.
Dependencies Developers may select and manage individual dependencies. Starter dependencies group common dependencies.
Application startup Depends on application type and deployment model. Commonly supports standalone execution with embedded servers for web applications.
Relationship Core framework. Built on Spring Framework and related Spring projects.

Spring Boot does not replace the Spring Framework. It makes many common Spring application configurations easier to create and maintain.


16. Spring Testing Architecture

Testing is an important part of Spring application development. Spring provides test support for unit testing, integration testing, application-context management, and web-layer testing.

Unit Testing

Unit tests verify an individual class in isolation. Constructor injection makes it easier to supply a mock dependency without starting the entire Spring container.

class PriceService {

    public double calculateTotal(
            double price, int quantity) {
        return price * quantity;
    }
}

This simple service can be tested using JUnit without initializing a Spring application context.

Integration Testing

Integration tests verify how multiple components work together. Spring's testing support can load an application context and provide access to configured beans.

Web-Layer Testing

Spring MVC Test and MockMvc can be used to test controller behavior without starting a real HTTP server in many common test scenarios.

Benefits of Spring Testing Support

  • Encourages separation between business logic and infrastructure.
  • Supports isolated unit tests and broader integration tests.
  • Helps verify dependency configuration.
  • Allows controllers and request mappings to be tested.
  • Helps identify configuration and transaction-related issues.

17. Practical Example: Building a Simple Spring Application

Consider a small application that provides a welcome message. It contains a service class and a REST controller. Spring manages the service bean and injects it into the controller.

Step 1: Create the Service

package com.example.service;

import org.springframework.stereotype.Service;

@Service
public class WelcomeService {

    public String getWelcomeMessage() {
        return "Welcome to the Spring Framework";
    }
}

Step 2: Create the Controller

package com.example.controller;

import com.example.service.WelcomeService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WelcomeController {

    private final WelcomeService welcomeService;

    public WelcomeController(
            WelcomeService welcomeService) {
        this.welcomeService = welcomeService;
    }

    @GetMapping("/api/welcome")
    public String welcome() {
        return welcomeService.getWelcomeMessage();
    }
}

Step 3: Configure the Application

For a Spring Boot project, a main application class can enable component scanning and bootstrap the application.

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(
            Application.class,
            args
        );
    }
}

Step 4: Run and Test

  1. Create a Spring Boot project with the web starter and compatible Java and Spring versions.
  2. Place the classes under the same root package or a scanned subpackage.
  3. Run the main application class.
  4. Send a GET request to http://localhost:8080/api/welcome.
  5. Verify that the response is Welcome to the Spring Framework.

What Happens Internally?

  • Spring Boot starts the application context.
  • Component scanning discovers the controller and service.
  • The IoC container creates and manages their beans.
  • Constructor injection supplies the service to the controller.
  • Spring MVC maps the HTTP request to the controller method.
  • The controller calls the service and returns the result.
  • The web infrastructure writes the result to the HTTP response.

18. Advantages of Spring Framework Architecture

  • Modularity: Applications can use only the modules they require.
  • Loose coupling: Dependency injection reduces direct dependencies between classes.
  • Maintainability: Clear separation of responsibilities makes changes easier to manage.
  • Testability: Components can be tested independently or together.
  • Database integration: Spring provides support for JDBC, ORM, and transaction management.
  • Web development: Spring MVC supports HTTP applications and REST endpoints.
  • Cross-cutting concerns: AOP can centralize concerns such as logging and transaction handling.
  • Integration support: Spring can work with many external libraries and enterprise systems.
  • Flexible configuration: Applications can use annotations, Java configuration, XML, or a combination.

19. Common Mistakes and Best Practices

Common Mistakes

  • Creating every dependency directly with new instead of using appropriate dependency injection.
  • Using field injection everywhere without considering testability.
  • Marking every class as a Spring component unnecessarily.
  • Mixing controller, business, and persistence responsibilities in a single class.
  • Assuming singleton beans are automatically thread-safe.
  • Using AOP without understanding proxy behavior.
  • Ignoring transaction boundaries when multiple database operations must succeed together.
  • Creating circular dependencies between services.
  • Writing integration tests for every small calculation instead of using simple unit tests where appropriate.

Best Practices

  • Prefer constructor injection for required dependencies.
  • Separate controllers, services, and repositories according to their responsibilities.
  • Use interfaces when they provide a meaningful abstraction or interchangeable implementation.
  • Keep business logic independent of web-specific concerns.
  • Use transaction management at appropriate service boundaries.
  • Keep singleton service objects stateless where possible.
  • Use configuration classes and component scanning consistently.
  • Write unit tests for business rules and integration tests for component interactions.
  • Understand which Spring features are needed before adding dependencies.
  • Keep Spring, Java, and third-party library versions compatible.

20. Practice Exercises

Exercise 1: Create a Spring Bean

Create a class called StudentService and register it as a Spring bean using @Component or @Service. Retrieve the bean from the application context and call one of its methods.

Exercise 2: Implement Dependency Injection

Create a NotificationService and inject it into a UserService using constructor injection. Verify that the user service can call the notification service.

Exercise 3: Compare Injection Types

Write small examples using constructor injection and setter injection. Explain which dependency is required and why one injection approach may be more appropriate than another.

Exercise 4: Configure Beans Using Java

Create an @Configuration class and define a bean using @Bean. Retrieve the bean from the application context.

Exercise 5: Build a REST API

Create a Spring MVC controller with endpoints for retrieving a welcome message and basic student information. Move business logic into a service class.

Exercise 6: Integrate a Database

Configure a data source and implement a repository that retrieves records from a sample database. Use Spring JDBC or JPA according to the project requirements.

Exercise 7: Apply AOP

Configure a simple logging aspect and verify that it runs before selected service methods. Test the behavior through the Spring-managed proxy.

Exercise 8: Write Tests

Write a unit test for a service class and an integration test that loads the Spring context. Compare their purpose, execution cost, and coverage.


21. Interview Questions and Answers

Q1. What is the Spring Framework?

Answer: Spring is an open-source Java framework that provides infrastructure for dependency injection, application configuration, web development, data access, transaction management, testing, and other enterprise application requirements.

Q2. What is Spring Framework architecture?

Answer: It is the modular organization of Spring's container, AOP, data access, web, messaging, and testing capabilities. Applications combine the modules required by their use cases.

Q3. What is IoC?

Answer: Inversion of Control is a design principle in which control over object creation and dependency management is transferred from application code to a container or framework.

Q4. What is Dependency Injection?

Answer: Dependency Injection is a technique in which an object's dependencies are supplied externally rather than created or located directly by that object.

Q5. What is a Spring bean?

Answer: A Spring bean is an object instantiated, configured, and managed by the Spring IoC container.

Q6. What is the difference between BeanFactory and ApplicationContext?

Answer: BeanFactory provides fundamental bean management. ApplicationContext adds application-level capabilities such as events, message resolution, and resource access, and is commonly used in standard applications.

Q7. Which dependency injection method is generally preferred?

Answer: Constructor injection is generally preferred for required dependencies because it makes dependencies explicit, supports final fields, and simplifies unit testing.

Q8. What is the purpose of the Spring Core Container?

Answer: It provides the infrastructure for creating, configuring, and managing beans, resolving dependencies, and accessing application context features.

Q9. What is Spring AOP?

Answer: Spring AOP supports the separation of cross-cutting concerns, such as logging and transaction handling, from the core business logic.

Q10. What is Spring MVC?

Answer: Spring MVC is a Servlet-based web framework that processes HTTP requests through components such as DispatcherServlet, handler mappings, controllers, and response-handling infrastructure.

Q11. What is DispatcherServlet?

Answer: DispatcherServlet is the front controller in Spring MVC. It coordinates request handling by working with configured mappings, handlers, and other MVC components.

Q12. What is the role of the Spring data access module?

Answer: It simplifies database integration, provides JDBC and ORM support, and integrates with transaction management.

Q13. What is the difference between Spring and Spring Boot?

Answer: Spring Framework provides the core application infrastructure. Spring Boot builds on it and simplifies configuration, dependency setup, and application startup through features such as auto-configuration and starter dependencies.

Q14. What is a bean scope?

Answer: A bean scope determines how Spring creates and shares instances. Common scopes include singleton and prototype, with additional web-specific scopes available in suitable environments.

Q15. How does Spring improve testability?

Answer: Dependency injection allows dependencies to be replaced with mocks or test implementations. Spring also provides support for application-context integration tests and web-layer testing.


22. Quick Revision Checklist

  • Understand the purpose of the Spring Framework.
  • Identify the major Spring architecture modules.
  • Explain IoC and Dependency Injection.
  • Understand beans and the IoC container.
  • Differentiate BeanFactory and ApplicationContext.
  • Recognize constructor, setter, and field injection.
  • Understand bean lifecycle and bean scopes.
  • Explain AOP terminology and proxy-based interception.
  • Understand Spring JDBC, ORM, and transaction support.
  • Describe the Spring MVC request lifecycle.
  • Differentiate Spring Framework from Spring Boot.
  • Practice configuration, REST controllers, dependency injection, and testing.

23. Conclusion

The Spring Framework provides a modular architecture for developing robust, maintainable Java applications. Its Core Container manages beans and dependencies, AOP supports cross-cutting concerns, data access modules simplify persistence, and the web layer supports HTTP applications and REST APIs. Spring's testing infrastructure also helps developers validate individual components and complete application workflows.

Understanding Spring architecture provides the foundation for learning advanced Java development topics such as Spring MVC, REST API development, Hibernate integration, transaction management, and enterprise application design.

Continue Learning with JustAcademy

Explore the Advance Java Training Course to continue learning Java enterprise development and related technologies.

Interested in learning more about the program? Register for a Course Demo.

Visit the JustAcademy Official Website to explore additional training opportunities.

Previous Next
whatsapp